//图表模拟数据
var conclusion = "经过数据分析，贵公司在这一个月中的共用能[power]KWh,预计使用电费[price]元,平均设备使用率为[avgUtilization],其中[deviceName]设备使用率最高,达到[maxUtilization]," +
    "用电质量问题,发生电压越载[overload]次,[overloadDeviceName]设备次数最高,共[totalOverload]次,三相不平衡[unbalance]次,[unbalanceDeviceName]设备次数最高,共[totalUnbalance]次,用电健康指数过低[overload]次,[]设备次数最高,共[]次,电能质量问题可能会对电力系统" +
    "及重要设备产生危害,影响企业的正常生产运营。";
var pie1_valueList = [
    {value: 0, name: '峰值'},
    {value: 0, name: '平值'},
    {value: 0, name: '谷值'}
];
var pie2_valueList = [
    {value: 0, name: '峰值'},
    {value: 0, name: '平值'},
    {value: 0, name: '谷值'}
];
var onPower = 0;
var beforePower = 0;
var lastYearPower = 0;
var onElectricityBill = 0;
var beforeElectricityBill = 0;
var lastYearElectricityBill = 0;
$(function () {
    // loadEnterprise();
    $('#company_name').html(sessionStorage.getItem("company_name"));
    chart_pie1.setOption(option_pie1);
    chart_pie2.setOption(option_pie1);
    chart_radar.setOption(option_radar);
    //图表赋值及lengend格式化，替换相应的数组，并重写lengend的formatter字段
    chart_pie1.setOption({
        legend: {
            formatter: function (name) {
                var index = 0;
                pie1_valueList.forEach(function (value, i) {
                    if (value.name == name) {
                        index = i;
                    }
                });
                return name + "：" + pie1_valueList[index].value + 'kWh';
            }
        },
        series: [{
            name: '电量',
            data: pie1_valueList
        }]
    })

    chart_pie2.setOption({
        legend: {
            formatter: function (name) {
                var index = 0;
                pie2_valueList.forEach(function (value, i) {
                    if (value.name == name) {
                        index = i;
                    }
                });
                return name + "：" + pie2_valueList[index].value + '万元';
            }
        },
        series: [{
            name: '电费',
            data: pie2_valueList
        }]
    })
    loadEnterpriseExtraData();

})

/*获取设备所有实时数据*/
function loadEnterpriseExtraData() {
    showLoading(LOADING);
    var passArray = [60, 60, 60, 70];
    $('#tb1_List tbody').empty();
    getJson('/deviceData/getElectricityParameters', {'month': $('#searchTimeBegin').val()}, 'GET', function (res) {
        var tr = '';
        var health = Number(0);
        var voltageDeviation = Number(0);
        var frequencyDeviation = Number(0);
        var unblance = Number(0);
        var loadRate = Number(0);
        var powerFactor = Number(0);
        //定义数组 用来存循环定义的对象
        var aa = [];
        for (var i = 0; i < res.length; i++) {
            var data = res[i];
            //定义对象  用来存不合格的数量 && 拼接的标签
            var Unqualified = {num: 0, str: ""};
            health += Number(data.health);
            voltageDeviation += Number(data.voltageDeviation);
            frequencyDeviation += Number(data.frequencyDeviation);
            unblance += Number(data.unblance);
            loadRate += Number(data.work);
            powerFactor += Number(data.powerFactor);
            var tr = '<tr>\n' +
                '<td>' + data.name + '</td>';
            if (data.voltageDeviation >= passArray[0]) {
                tr += '<td>合格</td>'
            } else {
                tr += '<td class="text-danger">不合格</td>';
                Unqualified.num += 1;
            }

            if (data.frequencyDeviation >= passArray[1]) {
                tr += '<td>合格</td>'
            } else {
                tr += '<td class="text-danger">不合格</td>';
                Unqualified.num += 1;
            }

            if (data.unblance >= passArray[2]) {
                tr += '<td>合格</td>'
            } else {
                tr += '<td class="text-danger">不合格</td>';
                Unqualified.num += 1;
            }

            if (data.powerFactor >= passArray[3]) {
                tr += '<td>合格</td>'
            } else {
                tr += '<td class="text-danger">不合格</td>';
                Unqualified.num += 1;
            }

            tr += '<td>' + data.loadRate + '%</td>' +
                '  </tr>';
            Unqualified.str = tr;
            aa.push(Unqualified);
        }
        /*根据不合格个数排序*/
        for (var i = 0; i < aa.length; i++) {
            for (var j = 0; j < aa.length - i - 1; j++) {
                if (aa[j].num < aa[j + 1].num) {
                    var emp = aa[j];
                    aa[j] = aa[j + 1];
                    aa[j + 1] = emp;
                }
            }
        }
        /*拼接排序好的html*/
        var strr = "";
        for (var i = 0; i < aa.length - 1; i++) {
            strr += aa[i].str;
        }

        $('#tb1_List tbody').append(strr);
        $('#jkzs_id').html(isNaN(health / res.length) ? 0 : Number((health / res.length).toFixed(1)));
        $('#ztpf_id').html(isNaN(health / res.length) ? 0 : Number((health / res.length).toFixed(1)) + '分');
        $('#glys_id').html(isNaN(powerFactor / res.length) ? 0 : Math.round(powerFactor / res.length) / 100);
        $('#plpc_id').html(isNaN(frequencyDeviation / res.length) ? 0 : Math.round(Number(frequencyDeviation / res.length) * 100) / 100 + '%');
        $('#dypc_id').html(isNaN(voltageDeviation / res.length) ? 0 : Math.round(Number(voltageDeviation / res.length) * 100) / 100 + '%');
        $('#sxbph_id').html(isNaN(unblance / res.length) ? 0 : Math.round(Number(unblance / res.length) * 100) / 100);
        $('#fzl_id').html(isNaN(loadRate / res.length) ? 0 : Math.round(loadRate / res.length) / 100 + '%');
        chart_radar.setOption({//用电分析
            series: [{
                data: [{
                    value: [
                        isNaN(voltageDeviation / res.length) ? 0 : Math.round(Number(voltageDeviation / res.length) * 100) / 100,
                        isNaN(frequencyDeviation / res.length) ? 0 : Math.round(Number(frequencyDeviation / res.length) * 100) / 100,
                        isNaN(unblance / res.length) ? 0 : Number(unblance / res.length).toFixed(2),
                        isNaN(loadRate / res.length) ? 0 : Number(loadRate / res.length).toFixed(2),
                        isNaN(powerFactor / res.length) ? 0 : Number(powerFactor / res.length).toFixed(2)]
                }]
            }]
        });
        hideLoading();
    });
    getJson('/deviceData/getOverviewOfEnergyUse', {'month': $('#searchTimeBegin').val()}, 'GET', function (res) {
        var data = res.lastMonth;
        onPower = 0;
        beforePower = 0;
        lastYearPower = 0;
        onElectricityBill = 0;
        beforeElectricityBill = 0;
        lastYearElectricityBill = 0;
        if (res.lastMonth) {
            onPower = res.lastMonth.power;
            onElectricityBill = res.lastMonth.bill;
        }
        if (res.previousMonth) {
            beforePower = res.previousMonth.power;
            beforeElectricityBill = res.previousMonth.bill;
        }
        if (res.lastYear) {
            lastYearPower = res.lastYear.power;
            lastYearElectricityBill = res.lastYear.bill;
        }
        $('#tjsc_id').html($('#searchTimeBegin').val());
        if (data && data.createTime) {
            $('#tjsc_id').html(data.createTime.substring(0, 7));
        }
        $('#tjsc_id').html($('#tjsc_id').text().replace('-', "年") + '月');
        switchMY(0);
        if (data) {
            pie1_valueList = [
                {
                    value: isNaN(Number(data.maxPower)) ? 0 : Number(data.maxPower).toFixed(2)
                    , name: '峰值'
                },
                {
                    value: isNaN(Number(data.avgPower)) ? 0 : Number(data.avgPower).toFixed(2)
                    , name: '平值'
                },
                {
                    value: isNaN(Number(data.minPower)) ? 0 : Number(data.minPower).toFixed(2)
                    , name: '谷值'
                }
            ];
            pie2_valueList = [
                {
                    value: isNaN(Number(data.maxBill)) ? 0 : (Number(data.maxBill) / 10000).toFixed(4)
                    , name: '峰值'
                },
                {
                    value: isNaN(Number(data.avgBill)) ? 0 : (Number(data.avgBill) / 10000).toFixed(4)
                    , name: '平值'
                },
                {
                    value: isNaN(Number(data.minBill)) ? 0 : (Number(data.minBill) / 10000).toFixed(4)
                    , name: '谷值'
                }
            ];
        } else {
            pie1_valueList = [
                {value: 0, name: '峰值'},
                {value: 0, name: '平值'},
                {value: 0, name: '谷值'}
            ];
            pie2_valueList = [
                {value: 0, name: '峰值'},
                {value: 0, name: '平值'},
                {value: 0, name: '谷值'}
            ];
        }
        chart_pie1.setOption({
            legend: {
                formatter: function (name) {
                    var index = 0;
                    pie1_valueList.forEach(function (value, i) {
                        if (value.name == name) {
                            index = i;
                        }
                    });
                    return name + "：" + pie1_valueList[index].value + 'kWh';
                }
            },
            series: [{
                data: pie1_valueList
            }]
        });
        chart_pie2.setOption({
            legend: {
                formatter: function (name) {
                    var index = 0;
                    pie2_valueList.forEach(function (value, i) {
                        if (value.name == name) {
                            index = i;
                        }
                    });
                    return name + "：" + pie2_valueList[index].value + '万元';
                }
            },
            series: [{
                data: pie2_valueList
            }]
        });
        $('#pjdj_id').html('平均电价：0元/kWh');
        if (data && !isNaN(Number(data.bill) / Number(data.power))) {
            $('#pjdj_id').html('平均电价：' + Number(Number(data.bill) / Number(data.power)).toFixed(4) + '元/kWh');
        }
        getJson('/deviceData/getReportConclusion', {'month': $('#searchTimeBegin').val()}, 'GET', function (res) {
            if (data && data['power'] && data['bill']) {
                $('#power').text(Math.round(data['power'] * 100) / 100);
                $('#price').text(Math.round(data['bill']) / 10000);
            } else {
                $('#power').text(0);
                $('#price').text(0);
            }
            if (res) {
                if (!isNull(res['avgUtilization'])) {
                    $('#avgUtilization').text(Math.round(res['avgUtilization'] * 100) / 100 + '%');
                } else {
                    $('#avgUtilization').parent().remove();
                }
                if (!isNull(res['deviceName'])) {
                    $('#deviceName').text(res['deviceName']);
                }
                if (!isNull(res['maxUtilization'])) {
                    $('#maxUtilization').text(Math.round(res['maxUtilization'] * 100) / 100 + '%');
                }
                if (!isNull(res['Overload'])) {
                    $('#overload').text(res['Overload']);
                }
                if (!isNull(res['overloadDeviceName'])) {
                    $('#overloadDeviceName').text(res['overloadDeviceName']);
                } else {
                    $('#overloadDeviceName').parent().remove();
                }
                if (!isNull(res['totalOverload'])) {
                    $('#totalOverload').text(res['totalOverload']);
                } else {
                    $('#totalOverload').parent().remove();
                }
                if (!isNull(res['unbalance'])) {
                    $('#unbalance').text(res['unbalance']);
                }
                if (!isNull(res['totalUnbalance'])) {
                    $('#totalUnbalance').text(res['totalUnbalance']);
                } else {
                    $('#totalUnbalance').parent().remove();
                }
                if (!isNull(res['unbalanceDeviceName'])) {
                    $('#unbalanceDeviceName').text(res['unbalanceDeviceName']);
                } else {
                    $('#unbalanceDeviceName').parent().remove();
                }
                if (!isNull(res['healthIndex'])) {
                    $('#healthIndex').text(res['healthIndex']);
                }
                if (!isNull(res['totalHealthIndex'])) {
                    $('#totalHealthIndex').text(res['totalHealthIndex']);
                } else {
                    $('#totalHealthIndex').parent().remove();
                }
                if (!isNull(res['healthIndexDevice'])) {
                    $('#healthIndexDevice').text(res['healthIndexDevice']);
                } else {
                    $('#healthIndexDevice').parent().remove();
                }
            }

        });
    });
}


/* 切换同比环比 */
function switchMY(num, e) {
    removeClass();
    if (num == 0) {
        var ratioPower = Number((onPower - beforePower) / beforePower);
        var ratioBill = Number((onElectricityBill - beforeElectricityBill) / beforeElectricityBill);
        var onPrice = Number(onElectricityBill / onPower);
        var beforePrice = Number(beforeElectricityBill / beforePower);
        var ratioPrice = (onPrice - beforePrice) / beforePrice;
        if (beforePower == 0) {
            $('#dl_id_i').html("暂无环比");
        } else {
            if (ratioPower < 0) {
                $('#dl_id').addClass('text-warning');
                $('#dl_id_i').addClass('icon-huanbizengchangshuai-xiajiang');
            } else {
                $('#dl_id').addClass('text-danger');
                $('#dl_id_i').addClass('icon-huanbizengchangshuai-shangsheng');
            }
            $('#dl_id_i').html(toPercent(ratioPower));
        }
        if (beforeElectricityBill == 0) {
            $('#df_id_i').text("暂无环比");
        } else {
            if (ratioBill < 0) {
                $('#df_id').addClass('text-warning');
                $('#df_id_i').addClass('icon-huanbizengchangshuai-xiajiang');
            } else {
                $('#df_id').addClass('text-danger');
                $('#df_id_i').addClass('icon-huanbizengchangshuai-shangsheng');
            }
            $('#df_id_i').text(toPercent(ratioBill));
        }
        if (beforePrice == 0 || isNaN(beforePrice)) {
            $('#dj_id_i').text("暂无环比");
        } else {
            if (ratioPrice < 0) {
                $('#dj_id').addClass('text-warning');
                $('#dj_id_i').addClass('icon-huanbizengchangshuai-xiajiang');
            } else {
                $('#dj_id').addClass('text-danger');
                $('#dj_id_i').addClass('icon-huanbizengchangshuai-shangsheng');
            }
            $('#dj_id_i').text(toPercent(ratioPrice));
        }
    } else {
        var ratioPower = Number((onPower - lastYearPower) / lastYearPower);
        var ratioBill = Number((onElectricityBill - lastYearElectricityBill) / lastYearElectricityBill);
        var onPrice = Math.round(Number(onElectricityBill / onPower) * 100 / 100);
        var beforePrice = Math.round(Number(lastYearElectricityBill / lastYearPower) * 100 / 100);
        if (isNaN(beforePrice)) {
            beforePrice = 0;
        }
        var YoYPrice = (onPrice - beforePrice) / beforePrice;
        if (lastYearPower == 0) {
            $('#dl_id_i').html("暂无同比");
        } else {
            if (ratioPower < 0) {
                $('#dl_id').addClass('text-warning');
                $('#dl_id_i').addClass('icon-huanbizengchangshuai-xiajiang');
            } else {
                $('#dl_id').addClass('text-danger');
                $('#dl_id_i').addClass('icon-huanbizengchangshuai-shangsheng');
            }
            $('#dl_id_i').html(toPercent(ratioPower));
        }
        if (lastYearElectricityBill == 0) {
            $('#df_id_i').text("暂无同比");
        } else {
            if (ratioBill < 0) {
                $('#df_id').addClass('text-warning');
                $('#df_id_i').addClass('icon-huanbizengchangshuai-xiajiang');
            } else {
                $('#df_id').addClass('text-danger');
                $('#df_id_i').addClass('icon-huanbizengchangshuai-shangsheng');
            }
            $('#df_id_i').text(toPercent(ratioBill));
        }
        if (beforePrice == 0 || isNaN(beforePrice)) {
            $('#dj_id_i').text("暂无同比");
        } else {
            if (YoYPrice < 0) {
                $('#dj_id').addClass('text-warning');
                $('#dj_id_i').addClass('icon-huanbizengchangshuai-xiajiang');
            } else {
                $('#dj_id').addClass('text-danger');
                $('#dj_id_i').addClass('icon-huanbizengchangshuai-shangsheng');
            }
            $('#dj_id_i').text(toPercent(YoYPrice));
        }
    }
    $(e).removeClass('btn-inactive').siblings().addClass('btn-inactive');
}


function removeClass() {
    $('#dl_id').removeClass('text-warning');
    $('#dl_id_i').removeClass('icon-huanbizengchangshuai-xiajiang');
    $('#dl_id').removeClass('text-danger');
    $('#dl_id_i').removeClass('icon-huanbizengchangshuai-shangsheng');
    $('#df_id').removeClass('text-warning');
    $('#df_id_i').removeClass('icon-huanbizengchangshuai-xiajiang');
    $('#df_id').removeClass('text-danger');
    $('#df_id_i').removeClass('icon-huanbizengchangshuai-shangsheng');
    $('#dj_id').removeClass('text-warning');
    $('#dj_id_i').removeClass('icon-huanbizengchangshuai-xiajiang');
    $('#dj_id').removeClass('text-danger');
    $('#dj_id_i').removeClass('icon-huanbizengchangshuai-shangsheng');
}

/* 导出图片 */
function downloadIMG(month) {
    downloadIMG_t('printDiv', '报告管理' + '2020年6月');
}

laydate.render({
    elem: '#searchTimeBegin',
    btns: ['clear', 'confirm'],
    type: 'month'
    , max: -30 //一月前

})

var chart_pie1 = echarts.init(document.getElementById('chart_pie1'));
var chart_pie2 = echarts.init(document.getElementById('chart_pie2'));
var chart_radar = echarts.init(document.getElementById('chart_radar'));

var option_pie1 = {
    color: ['#D97D34', '#D9B65C', '#0085CB'],
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)',
        backgroundColor: 'rgba(39, 71, 105, 0.7)'
    },
    legend: {
        orient: 'vertical',
        top: '260',
        icon: 'path://M0 0m407.253608 0l814.507217 0q407.253608 0 407.253608 407.253608l0 0q0 407.253608-407.253608 407.253609l-814.507217 0q-407.253608 0-407.253608-407.253609l0 0q0-407.253608 407.253608-407.253608Z',
        itemWidth: 32,
        itemHeight: 16,
        itemGap: 15,//每个图例间距
        textStyle: {
            fontSize: 16,
            color: ['#D97D34', '#D9B65C', '#0085CB'],
            padding: [0, 10]//文字与图标间距
        }
    },
    series: [{
        name: '电量',
        type: 'pie',
        radius: [58, 95],
        center: ['50%', '135'],
        label: {
            formatter: '{b}{d}%',
            fontSize: 16
        },
        data: []
    }]
};
var option_radar = {//用电分析
    color: '#1890FF',
    tooltip: {
        backgroundColor: 'rgba(39, 71, 105, 0.7)'
    },
    radar: {
        name: {
            textStyle: {
                color: '#fff',
                lineHeight: 14
            }
        },
        center: ['50%', '57%'],
        radius: '80%',
        indicator: [
            {name: '电压偏差', max: 100},
            {name: '频率\n偏差', max: 100},
            {name: '三相不平衡', max: 100},
            {name: '负载率', max: 100},
            {name: '功率\n因数', max: 100}
        ],
        axisLine: {
            lineStyle: {
                color: '#D1E6F9'
            }
        },
        splitLine: {
            lineStyle: {
                color: ['#707070']
            }
        },
        splitArea: {
            areaStyle: {
                color: ['rgba(250,250,250,0.1)', 'rgba(200,200,200,0.1)']
            }
        }
    },
    series: [{
        name: '用电分析',
        type: 'radar',
        showSymbol: false,
        areaStyle: {
            color: 'rgba(13, 98, 177, 0.3)'
        },
        lineStyle: {
            color: '#1890FF',
            width: 2
        },
        data: [{
            value: [0, 0, 0, 0, 0]
        }]
    }]
};



